package cn.ymatrix.mxgateSDKRabbitMQTOYMatrix.rabbitmqOperate;

import cn.ymatrix.utils.Config;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;

public class RabbitMQDataConsumer {
  private static final String QUEUE_NAME = Config.getQueueName();
  private static final String QUEUE_HOST = Config.getQueueHost();
  private static final String QUEUE_USERNAME = Config.getQueueUserName();
  private static final String QUEUE_PASSWORD = Config.getQueuePassword();
  private static final boolean queueISexist = Config.isQueueISexist();

  private static final int ThreadSleepTime = Config.getQueueThreadSleepTime();

  public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(QUEUE_HOST);
    factory.setUsername(QUEUE_USERNAME);
    factory.setPassword(QUEUE_PASSWORD);
    try (Connection connection = factory.newConnection();
        Channel channel = connection.createChannel()) {
      channel.queueDeclare(QUEUE_NAME, queueISexist, false, false, null);
      DeliverCallback deliverCallback =
          (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
          };
      boolean autoAck = true;
      channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {});
      while (true) {
        // 阻塞线程，避免立即退出
        Thread.sleep(ThreadSleepTime);
      }
    }
  }
}
